import {LogCategory, logger} from '../../logger';
import {BaseStoreService} from './BaseStoreService';
import {BookmarksSchema} from '../types';

/**
 * 书签存储服务类
 * 负责管理用户的书签数据
 */
export class BookmarksService extends BaseStoreService<BookmarksSchema> {
  private static instance: BookmarksService;

  /**
   * 私有构造函数
   */
  private constructor() {
    super('Bookmarks', {bookmarks: []});
  }

  /**
   * 获取BookmarksService单例实例
   */
  public static getInstance(): BookmarksService {
    if (!BookmarksService.instance) {
      BookmarksService.instance = new BookmarksService();
    }
    return BookmarksService.instance;
  }

  /**
   * 获取书签数据
   */
  public getBookmarks(): BookmarksSchema['bookmarks'] {
    logger.debug(this.moduleName, LogCategory.SYSTEM, '获取书签数据');
    return this.store.get('bookmarks');
  }

  /**
   * 添加书签
   * @param bookmark 书签数据
   */
  public addBookmark(bookmark: Omit<BookmarksSchema['bookmarks'][0], 'id' | 'createdAt'>) {
    const bookmarks = this.getBookmarks();
    const newBookmark = {
      ...bookmark,
      id: Date.now().toString(),
      createdAt: Date.now()
    };

    logger.info(this.moduleName, LogCategory.SYSTEM, `添加书签: ${newBookmark.title}, URL: ${newBookmark.url}`);

    this.store.set('bookmarks', [...bookmarks, newBookmark]);
    return newBookmark;
  }

  /**
   * 删除书签
   * @param id 书签ID
   */
  public deleteBookmark(id: string): boolean {
    try {
      const bookmarks = this.getBookmarks();
      const bookmarkIndex = bookmarks.findIndex(b => b.id === id);

      if (bookmarkIndex === -1) {
        logger.warn(this.moduleName, LogCategory.SYSTEM, `未找到要删除的书签: ${id}`);
        return false;
      }

      const bookmark = bookmarks[bookmarkIndex];
      logger.info(this.moduleName, LogCategory.SYSTEM, `删除书签: ${bookmark.title}, URL: ${bookmark.url}`);

      // 处理文件夹嵌套关系
      if (bookmark.type === 'folder') {
        // 如果是文件夹，递归删除其中的书签
        this.deleteBookmarksInFolder(id, bookmarks);
      }

      // 从父文件夹的children中删除
      if (bookmark.parentId) {
        const parentIndex = bookmarks.findIndex(b => b.id === bookmark.parentId);
        if (parentIndex !== -1 && bookmarks[parentIndex].children) {
          const parent = bookmarks[parentIndex];
          const updatedChildren = parent.children!.filter(childId => childId !== id);

          // 更新父文件夹
          bookmarks[parentIndex] = {
            ...parent,
            children: updatedChildren
          };
        }
      }

      // 删除书签本身
      const updatedBookmarks = bookmarks.filter(b => b.id !== id);
      this.store.set('bookmarks', updatedBookmarks);

      return true;
    } catch (error) {
      logger.error(this.moduleName, LogCategory.SYSTEM, `删除书签失败: ${id}`, error);
      return false;
    }
  }

  /**
   * 递归删除文件夹中的所有书签
   * @param folderId 文件夹ID
   * @param bookmarks 所有书签列表
   */
  private deleteBookmarksInFolder(folderId: string, bookmarks: BookmarksSchema['bookmarks']): void {
    const folder = bookmarks.find(b => b.id === folderId);
    if (!folder || !folder.children || folder.children.length === 0) return;

    logger.debug(this.moduleName, LogCategory.SYSTEM, `删除文件夹中的书签: ${folder.title}, 共${folder.children.length}项`);

    // 处理文件夹中的每个子项
    for (const childId of folder.children) {
      const child = bookmarks.find(b => b.id === childId);
      if (!child) continue;

      // 如果子项也是文件夹，递归处理
      if (child.type === 'folder' && child.children && child.children.length > 0) {
        this.deleteBookmarksInFolder(childId, bookmarks);
      }
    }
  }

  /**
   * 清理存储数据
   */
  public cleanupStore(): void {
    // 书签数据一般不需要清理
    logger.debug(this.moduleName, LogCategory.SYSTEM, '书签数据不需要清理');
  }
}
